import 'package:dio/dio.dart';
import 'package:hotpot/http/interceptors/dy_cookie_manager.dart';
import 'package:hotpot/route/routes.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

typedef DyExceptionConfirmCallback = void Function();

/// 自定义异常
class AppException implements Exception {
  final String _message;
  final int _code;

  final DyExceptionConfirmCallback? _confirmCallback;

  AppException(this._code, this._message, [this._confirmCallback]) {
    Get.defaultDialog(
      title: _code == -1 ? '提示' : _code.toString(),
      titleStyle: const TextStyle(color: Colors.red),
      contentPadding: const EdgeInsets.only(bottom: 0, left: 5, right: 5),
      titlePadding: const EdgeInsets.symmetric(vertical: 20),
      radius: 8,
      middleText: _message,
      actions: [
        SizedBox(
          width: double.infinity,
          child: TextButton(
            child: const Text('确认'),
            onPressed: () {
              _confirmCallback == null ? Get.back() : _confirmCallback!();
            },
          ),
        )
      ],
    );
  }

  @override
  String toString() {
    return "$_code$_message";
  }

  factory AppException.create(DioException error) {
    switch (error.type) {
      case DioExceptionType.cancel:
        return AppException(-1, "请求取消");
      case DioExceptionType.connectionTimeout:
        return AppException(-1, "连接超时");
      case DioExceptionType.sendTimeout:
        return AppException(-1, "请求超时");
      case DioExceptionType.receiveTimeout:
        return AppException(-1, "响应超时");
      case DioExceptionType.badResponse:
        {
          try {
            int errCode = error.response!.statusCode ?? -1;
            switch (errCode) {
              case 400:
                return AppException(errCode, "请求错误");
              case 401:
                return AppException(errCode, "没有权限");
              case 403:
                return AppException(errCode, "服务器拒绝执行");
              case 404:
                return AppException(
                    errCode, "会话已过期，请重新登录", sessionExpiredCallback);
              case 405:
                return AppException(errCode, "请求方法被禁止");
              case 500:
                return AppException(errCode, "服务器内部错误");
              case 502:
                return AppException(errCode, "无效的请求");
              case 503:
                return AppException(errCode, "服务器挂了");
              case 505:
                return AppException(errCode, "不支持HTTP协议请求");
              default:
                return AppException(
                    errCode, error.response!.statusMessage ?? '未知错误');
            }
          } on Exception catch (_) {
            return AppException(-1, "未知错误");
          }
        }
      default:
        var message = error.error is DioException ? (error.error as DioException).message : null;
        return AppException(-1, message ?? error.message ?? '');
    }
  }

  static void sessionExpiredCallback() async {
    await DyCookieManager.deleteCookies();
    // await DySecureStorage.deleteData('isLogin');
    Get.offAllNamed(Routes.splash);
  }
}
